package mainprocess

import (
	"dev_gw/common"
	"dev_gw/device"
	mqttclient "dev_gw/mqttClient"
	mqttserver "dev_gw/mqttServer"
	msgobj "dev_gw/msgObj"
	"dev_gw/point"
	"time"
)

type MainProcess struct {
	_device     *device.Device
	_mqtt       *mqttclient.MqttClient
	_mqttServer *mqttserver.MqttServer
}

func (m *MainProcess) onApOpen() {
	m._mqtt.Publish("v1/app/dev_gw/0/point/report", msgobj.NewAppReportMsg(common.ProtocolName, msgobj.NewAppReportDev(common.ProcessName, msgobj.NewAppReportPoint("wifi0ApState", m._device.PointValue("wifi0ApState")))).ToJson())
}

func (m *MainProcess) sendAppBeatheartThread() {
	for {
		time.Sleep(time.Second * 3)
		if m._mqtt.IsConnected() {
			m._mqtt.Publish("v1/app/"+common.ProcessName+"/0/point/report", msgobj.NewAppHeartBeat().ToJson())
		}

		time.Sleep(time.Second * 17)
	}
}

func Start() {
	mp := &MainProcess{
		_device: device.NewDevice(),
		_mqtt:   mqttclient.NewMqttClient(mqttclient.ClientId("dev_gw")),
	}

	mp._device.Insert("sn", point.NewSnPoint()).
		Insert("softwareVersion", point.NewSoftwareVersionPoint()).
		Insert("hardwareVersion", point.NewHardwareVersionPoint()).
		Insert("cpuTemplate", point.NewCpuTemplatePoint()).
		Insert("model", point.NewModelPoint()).
		Insert("wan?IpAllocation", point.NewWanXIpAllocationPoint()).
		Insert("wan?Ip", point.NewWanXIpPoint()).
		Insert("wan?Dns", point.NewWanXDnsPoint()).
		Insert("wan?Mac", point.NewWanXMacPoint()).
		Insert("wan?SubnetMask", point.NewWanXSubNetMaskPoint()).
		Insert("wan?Gateway", point.NewWanXGatewayPoint()).
		Insert("wanCount", point.NewWanCountPoint()).
		Insert("ntpServer", point.NewNtpServerPoint()).
		Insert("timeZone", point.NewTimeZonePoint()).
		Insert("wan?Connect", point.NewWanXConnectPoint()).
		Insert("wifi?ApSsid", point.NewWifiXApSsidPoint()).
		Insert("wifi?ApPasswd", point.NewWifiXApPasswordPoint()).
		Insert("wifi?ApClose", point.NewWifiXApClosePoint()).
		Insert("wifi?ApOpen", point.NewWifiXApOpenPoint(mp.onApOpen)).
		Insert("wifi?ApState", point.NewWifiXApStatePoint()).
		Insert("date", point.NewDatePoint()).
		Insert("upgrade", point.NewUpgradePoint()).
		Insert("kernelVersion", point.NewKernelVersionPoint()).
		Insert("cpuArch", point.NewCpuArchPoint()).
		Insert("cpuClockSpeed", point.NewCpuSpeedPoint()).
		Insert("diskSize", point.NewCpuDiskSizePoint()).
		Insert("memorySize", point.NewCpuMemorySizePoint()).
		Insert("rs485Count", point.NewRs485CountPoint()).
		Insert("rs485?Port", point.NewRs485XPortPoint()).
		Insert("chipid", point.NewChipIdPoint())

	mp._mqttServer = mqttserver.NewMqttServer(mp._mqtt, mp._device)
	mp._mqttServer.Start()
	go mp.sendAppBeatheartThread()

}
